﻿using MLog.Helpers;
using UnityEngine;

namespace MLog.Core.Appender {
    public class ConsoleAppender : BaseAppender<LoggerEvent> {
        protected override void DoAppend0(LoggerEvent @event) {
            var sb      = FormatterUtils.Format(@event, Pattern);
            var logType = ConvertToLogType(@event.Level);
#if UNITY_2017
            Debug.unityLogger.Log(logType, (object) sb, @event.Context);
#elif UNITY_5_3_OR_NEWER
            Debug.logger.Log(logType, (object) sb, @event.Context);
#else
            switch (logType) {
                case LogType.Log:
                    Debug.Log(sb, @event.Context);
                    break;
                case LogType.Assert:
                    Debug.LogAssertion(sb, @event.Context);
                    break;
                case LogType.Warning:
                    Debug.LogWarning(sb, @event.Context);
                    break;
                case LogType.Error:
                    Debug.LogError(sb, @event.Context);
                    break;
                case LogType.Exception:
                    Debug.LogException(@event.Exception, @event.Context);
                    break;
            }
#endif
        }

        private static LogType ConvertToLogType(LogLevel level) {
            switch (level) {
                case LogLevel.Debug:
                case LogLevel.Info:
                    return LogType.Log;
                case LogLevel.Error:
                    return LogType.Error;
                case LogLevel.Warning:
                    return LogType.Warning;
            }

            // Note: never
            return LogType.Assert;
        }
    }
}